package util;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.logging.Level;
import java.util.logging.Logger;

//http://www.rgagnon.com/javadetails/java-0416.html
//http://stackoverflow.com/questions/304268/using-java-to-get-a-files-md5-checksum
public class MD5Checksum {
    //Public methods
    public static String getMD5Checksum(String filename) throws FileNotFoundException {
        String result = "";
        byte[] b = createChecksum(filename);
        
        for (int i = 0; i < b.length; i++) {
            result += Integer.toString((b[i] & 0xff) + 0x100, 16).substring(1);
        }
        
        return result;
    }
    
    
    //Private methods
    private static byte[] createChecksum(String filename) throws FileNotFoundException {
        MessageDigest complete = null;
        InputStream fis = null;
        
        int read = 0;
        byte[] buffer = new byte[1024];
        
        try {
            fis = new FileInputStream(filename);
            complete = MessageDigest.getInstance("MD5");
            
            do {
                read = fis.read(buffer);
                if (read > 0) complete.update(buffer, 0, read);
            } while (read != -1);
            
            fis.close();
        } catch (IOException ex) {
            Logger.getLogger(MD5Checksum.class.getName()).log(Level.SEVERE, null, ex);
        } catch (NoSuchAlgorithmException ex) {
            Logger.getLogger(MD5Checksum.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        return complete.digest();
   }
}